import WxValidate from '../../../utils/WxValidate.js';
import http from '../../../utils/http.js';
import ocr from '../../../utils/ocr.js';

import {getDicts} from '../../../utils/dict.js';

const {
  $Message
} = require('../../../component/iview/base/index');

//基本信息
const baseField = [{
    "text": "过户类型",
    "field": "transferType",
    select: true,
  },
  // {
  //   "text": "业务类型",
  //   "field": "tradeVehicleType",
  //   select: true,
  // }, 
  {
    "text": "转入地",
    "field": "destination",
    // region: true,
    choose: true
  }, {
    "text": "车辆价格",
    "field": "amount",
    rule: {
      "required": true,
      "digits": true,
      //"min": 1
    },
    message: {
      "required": "车辆价格不能为空",
      "digits": "车辆价格只能是数字",
      // "min": "车辆价格需大于0"
    }
  }
];

const vehicleField = [{
    "text": "登记证编号",
    "field": "vehicle.registerNo",
    "scan": true,
    rule: {
      "required": true,
      "maxlength": 12,
      "minlength": 12,
      "number": true,
    },
    message: {
      "required": "登记证书编号不能为空",
      "maxlength": "登记证书编号不能超过12个字符",
      // "enNum": "登记证书编号只能是英文和数字"
      "number": "登记证书编号只能是数字"
    }
  }, {
    "text": "车架号",
    "field": "vehicle.vin",
    rule: {
      "required": true,
      "maxlength": 32,
      "enNum": true,
    },
    message: {
      "required": "车架号不能为空",
      "maxlength": "车架号不能超过32个字符",
      "enNum": '车架号只能输入英文和数字'
    }
  }, {
    "text": "车牌号码",
    "field": "vehicle.plateNo",
    rule: {
      "required": true,
      "plateNo": true
    },
    message: {
      "required": "车牌号码不能为空"
    }
  }, {
    "text": "品牌型号",
    "field": "vehicle.brandModel",
    rule: {
      "required": true,
      "maxlength": 64,
    },
    message: {
      "required": "品牌型号不能为空",
      "maxlength": "品牌型号不能超过64个字符",
    }
    // }, {
    //   "text": "车辆品牌",
    //   "field": "vehicle.brand",
    //   rule: {
    //     //"required": true,
    //     "maxlength": 64,
    //   },
    //   message: {
    //     //"required": "车辆品牌不能为空",
    //     "maxlength": "车辆品牌不能超过64个字符",
    //   }
    // }, {
    //   "text": "车辆型号",
    //   "field": "vehicle.model",
    //   rule: {
    //     //"required": true,
    //     "maxlength": 64,
    //   },
    //   message: {
    //     //"required": "车辆型号不能为空",
    //     "maxlength": "车辆型号不能超过64个字符",
    //   }
  },
  {
    "text": "发动机号",
    "field": "vehicle.engineNo",
    rule: {
      // "required": true,
      "maxlength": 64,
      "lineEnNum": true
    },
    message: {
      // "required": "发动机号不能为空",
      "maxlength": "发动机号不能超过64个字符",
      "lineEnNum": "发动机号只能是英文和数字和横杠"
    }
  }, {
    "text": "发动机型号",
    "field": "vehicle.engineModel",
    rule: {
      // "required": true,
      "maxlength": 64,
      "lineEnNum": true
    },
    message: {
      // "required": "发动机型号不能为空",
      "maxlength": "发动机型号不能超过64个字符",
      "lineEnNum": "发动机型号只能是英文和数字和横杠"
    }
  }, {

    "text": "出厂日期",
    "field": "vehicle.productionDate",
    date: true,
  }, {
    "text": "车辆类型",
    "field": "vehicle.vehicleType",
    select: true
  }, {
    "text": "燃油种类",
    "field": "vehicle.fuelType",
    select: true
  }, {
    "text": "使用性质",
    "field": "vehicle.useProperty",
    select: true
  }, {
    "text": "是否进口车",
    "field": "vehicle.isImported",
    select: true
  }, {
    "text": "排放标准",
    "field": "vehicle.emissionStandard",
    select: true
  }, {
    "text": "号牌种类",
    "field": "vehicle.plateType",
    select: true
  }
];

const buyer = [{
    //   "text": "证件类型",
    //   "field": "buyer.creditType",
    //   select: true
    // }, {
    "text": "证件编号",
    "field": "buyer.creditNo",
    rule: {
      "required": true,
      "creditNo": true
    },
    message: {
      "required": "证件编号不能为空",
      "creditNo": "请输入正确的证件编号"
    }
  }, {
    "text": "买方名称",
    "field": "buyer.name",
    rule: {
      "required": true,
      "maxlength": 32
    },
    message: {
      "required": "买方名称不能为空",
      "maxlength": "买方名称不能超过32个字符"
    }
  }, {
    "text": "居住地址",
    "field": "buyer.residenceAddress",
    "textarea": true,
    rule: {
      "required": true,
      "maxlength": 128
    },
    message: {
      "required": "居住地址不能为空",
      "maxlength": "居住地址不能超过128个字符"
    }
  },
  {
    "text": "联系电话",
    "field": "buyer.tel",
    rule: {
      "required": true,
      "tel": true
    },
    message: {
      "required": "联系电话不能为空",
      "tel": "电话号码不正确"
    }

  },
];

const seller = [{
    //   "text": "证件类型",
    //   "field": "seller.creditType",
    //   select: true
    // }, {
    "text": "证件编号",
    "field": "seller.creditNo",
    rule: {
      "required": true,
      "creditNo": true
    },
    message: {
      "required": "证件编号不能为空",
      "creditNo": "请输入正确的证件编号"
    }
  }, {
    "text": "卖方名称",
    "field": "seller.name",
    rule: {
      "required": true,
      "maxlength": 32
    },
    message: {
      "required": "卖方名称不能为空",
      "maxlength": "卖方名称不能超过32个字符"
    }
  }, {
    "text": "居住地址",
    "field": "seller.residenceAddress",
    "textarea": true,
    rule: {
      "required": true,
      "maxlength": 128
    },
    message: {
      "required": "居住地址不能为空",
      "maxlength": "居住地址不能超过128个字符"
    }
  },
  {
    "text": "联系电话",
    "field": "seller.tel",
    rule: {
      "required": true,
      "tel": true
    },
    message: {
      "required": "联系电话不能为空",
      "tel": "电话号码不正确"
    }
    //暂时不要户籍地址
    // }, {
    //   "text": "户籍地址",
    //   "field": "seller.censusAddress",
    //   rule: {
    //     "maxlength": 128
    //   },
    //   message: {
    //     "maxlength": "户籍地址不能超过128个字符"
    //   }
  },
];


Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeheight: 0,
    commission: null, //本次交易的费用
    show: false, //是否弹窗
    currentStep: 0,
    formField: [
      baseField, vehicleField, buyer, seller
    ],
    stu:{
      "name":"",

    },
    // formField: {
    //   vehicle: vehicleField,
    //   buyer: person,
    //   seller: person
    // },
    files: {},
    filesFlag: {},
    filesField: [{
        text: '行驶证',
        field: 'vehicleLicense',
        hidden: true,
      }, {
        text: '机动车登记证首页',
        field: 'vehicleRegister',
        "required": true,
      },
      {
        text: '机动车登记证尾页',
        field: 'vehicleRegister_1',
        "required": true,
      }, {
        text: '买家证件照（正）',
        field: 'buyerCreditFront',
        hidden: true,
      }, {
        text: '买家证件照  （反）',
        field: 'buyerCreditBack'
      }, {
        text: '卖家证件照（正）',
        field: 'sellerCreditFront',
        hidden: true,
      }, {
        text: '卖家证件照  （反）',
        field: 'sellerCreditBack'
      }
    ],
    formDict: {
      "vehicle.isImported": [{
        code: 0,
        name: '非进口车'
      }, {
        code: 1,
        name: '进口车'
      }]
    },
    formData: {
      "vehicle.isImported": 0,
      "destination": '福建省厦门市',
      "seller.creditType": "P1",
      "buyer.creditType": "P1",
    },
    formSelectData: {
      "vehicle.isImported": 0
    },

    ocrFile: [{
      step: 1,
      field: 'vehicleLicense',
      text: '请上传行驶证主页照片，将自动识别信息',
      bgClass: 'vehicle-license-image'
    }, {
      step: 2,
      field: 'buyerCreditFront',
      text: '请上传买家证件正面照片，将自动识别信息',
      bgClass: 'id-card-image',
      creditTypeField: "buyer.creditType",
      bgClass: {
        "P1": 'id-card-image',
        "C3": 'business-license-image',
      }
    }, {
      step: 3,
      field: 'sellerCreditFront',
      text: '请上传卖家证件正面照片，将自动识别信息',
      creditTypeField: "seller.creditType",
      bgClass: {
        "P1": 'id-card-image',
        "C3": 'business-license-image',
      }
    }],

    confirmShow: false, //用来展示是否切换个人和企业
    confirmField: '', //确定要更改的字段
    confirmValue: '', //确定要更改后的值
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let dictFieldArray = ["vehicle.vehicleType", "vehicle.fuelType",
      "vehicle.useProperty", "vehicle.emissionStandard",
      "vehicle.plateType",
      //"buyer.creditType", "seller.creditType",
      "transferType",
      "tradeVehicleType"
    ];
    let dictCategoryArray = ["VEHICLE_TYPE", "VEHICLE_FUEL_TYPE",
      "VEHICLE_USE_PROPERTY", "VEHICLE_EMISSION_STANDARD",
      "VEHICLE_PLATE_TYPE",
      //"CREDIT_TYPE", "CREDIT_TYPE",
      "Transfer_Type",
      "TRADE_VEHICLE_TYPE"
    ];
  
    // for (let i = 0; i < dictFieldArray.length; i++) {
    //   //加载相关字典
    //   this.loadDict(dictCategoryArray[i], dictFieldArray[i]);
    // }

    //   加载相关字典
    this.loadDict(dictCategoryArray, dictFieldArray);


    this.initValidate();
    if (options.applicationId != null) {

      //加载要修改的数据
      http.request({
        url: '/wxApplication/findApplicationInfo',
        data: {
          applicationId: options.applicationId
        },
        success: (res) => {
          this.transferData(res, "buyer");
          this.transferData(res, "seller");
          this.transferData(res, "vehicle");
          // this.transferData(res, "image");
          //delete res["image"];
          this.transferData(res, "ticket");

          let filesFlag = {};
          let image = {};
          // console.log(res)
          if (res["image"] != null) {
            let array = this.data.filesField;
            for (let i = 0; i < array.length; i++) {
              let field = array[i].field;
              if (res["image"][field] != null && res["image"][field] != '') {
                let src = http.apiUrl + http.imgUrl + "?imagePath=" + res["image"][field] +
                  "&" + wx.getStorageSync("sessionid")
                image[field] = encodeURI(src);
                filesFlag[field] = 0; // 0表示这是之前上传过的，1表示是新上传的
              }
            }
          }

          let formSelectData = this.data.formSelectData;
          for (let i = 0; i < dictFieldArray.length; i++) {
            this.dictToIndex(dictFieldArray[i], res[dictFieldArray[i]], formSelectData);
          }
          // this.dictToIndex("vehicle.vehicleType", res["vehicle.vehicleType"], formSelectData);
          // this.dictToIndex("vehicle.fuelType", res["vehicle.fuelType"], formSelectData);
          // this.dictToIndex("vehicle.useProperty", res["vehicle.useProperty"], formSelectData);
          // this.dictToIndex("vehicle.emissionStandard", res["vehicle.emissionStandard"], formSelectData);
          // this.dictToIndex("vehicle.plateType", res["vehicle.plateType"], formSelectData);
          // this.dictToIndex("buyer.creditType", res["buyer.creditType"], formSelectData);
          // this.dictToIndex("seller.creditType", res["seller.creditType"], formSelectData);
          formSelectData["vehicle.isImported"] = res["vehicle.isImported"];

          this.setData({
            formData: res,
            formSelectData: formSelectData,
            files: image,
            filesFlag: filesFlag
          });
        }
      });
      // } else {
      //   let formData = {};
      //   let formSelectData = {};
      //   for (let i = 0; i < dictFieldArray.length; i++) {
      //     var dict = this.data.formDict[dictFieldArray[i]];
      //     console.info(this.data.formDict);
      //     console.info(this.data.formDict[dictFieldArray[i]]);
      //     console.info(dictFieldArray[i]);
      //     if (dict != null && dict.length > 0) {
      //       let code = this.data.formDict[dictFieldArray[i]].code;
      //       formData[dictFieldArray[i]] = code;
      //       formSelectData[dictFieldArray[i]] = 0;
      //     }
      //   }
      //   this.setData({
      //     formData: formData,
      //     formSelectData: formSelectData
      //   });
      //   console.info(this.data)
    }

    //车辆列表跳转过户申请
    if (options.vehicleId != null) {
      let that =this;
      let  vehicleId =options.vehicleId;
      http.request({
        url: '/vehicleInfo/query/id',
        method:"GET",
        data: {
          id: vehicleId
        },
        success: (res) => {
          console.log(res)
          var formdata = that.data.formData;
          formdata['vehicle.brandModel'] = res.brandModel;
          formdata['fromMall'] =1;
          formdata['seller.name'] = res.owner;
          formdata['seller.residenceAddress'] = res.ownerAddress;
          formdata['vehicle.plateNo'] =  res.plateNo;
          formdata['vehicle.vin'] =  res.vin;
          formdata['vehicleId'] =  vehicleId;
          formdata['amount'] =  res.price *10000;
          formdata["image"] = {};
          //图片处理
          
          let filesFlag = {};
          let image = {};
          //行驶证
          formdata["image"]["vehicleLicense"] = res["vehicleImages"]["certificationImgs"]["licenseImg"];
          let vehicleLicense = http.apiUrl + http.imgUrl + "?imagePath=" + formdata["image"]["vehicleLicense"] + "&"+wx.getStorageSync("sessionid");
          image['vehicleLicense'] = encodeURI(vehicleLicense);
          filesFlag['vehicleLicense'] = 0; 
          //登记证首页
          //可能存在未传的情况
          if( res["vehicleImages"]["certificationImgs"]["registration12Img"]){
            formdata["image"]["vehicleRegister"] = res["vehicleImages"]["certificationImgs"]["registration12Img"];
            let vehicleRegister = http.apiUrl + http.imgUrl + "?imagePath=" + formdata["image"]["vehicleRegister"] +
            "&" + wx.getStorageSync("sessionid");
            image['vehicleRegister'] = encodeURI(vehicleRegister);
            filesFlag['vehicleRegister'] = 0; 
          }
 
          //登记证末页
          if(res["vehicleImages"]["certificationImgs"]["registrationLastImg"]){
            formdata["image"]["vehicleRegister_1"] = res["vehicleImages"]["certificationImgs"]["registrationLastImg"];
            let vehicleRegister_1 = http.apiUrl + http.imgUrl + "?imagePath=" 
              + formdata["image"]["vehicleRegister_1"] + "&" + wx.getStorageSync("sessionid");
            image['vehicleRegister_1'] = encodeURI(vehicleRegister_1);
            filesFlag['vehicleRegister_1'] = 0; 
          }

          
          //formdata['image'] = image;
          
          that.setData({
            formData:formdata,
            files: image,
            filesFlag: filesFlag
            // formData.vehicle.plateNo:res.brandModel,
          })
          // that.setData({
          //    [sellername]:res.owner,
          //    [sellerresidenceAddress]:res.ownerAddress,
          //    [vehiclevin]:res.vin,
          //    [vehicleplateNo]:,
          //    [vehiclebrandModel]: res.brandModel
          // })
        //   this.transferData(res, "buyer");
        //   this.transferData(res, "seller");
        //   this.transferData(res, "vehicle");
        //   // this.transferData(res, "image");
        //   //delete res["image"];
        //   this.transferData(res, "ticket");

        //   let filesFlag = {};
        //   let image = {};
        //   // console.log(res)
        //   if (res["image"] != null) {
        //     let array = this.data.filesField;
        //     for (let i = 0; i < array.length; i++) {
        //       let field = array[i].field;
        //       if (res["image"][field] != null && res["image"][field] != '') {
        //         let src = http.apiUrl + http.imgUrl + "?imagePath=" + res["image"][field] +
        //           "&" + wx.getStorageSync("sessionid")
        //         image[field] = encodeURI(src);
        //         filesFlag[field] = 0; // 0表示这是之前上传过的，1表示是新上传的
        //       }
        //     }
        //   }

        //   let formSelectData = this.data.formSelectData;
        //   for (let i = 0; i < dictFieldArray.length; i++) {
        //     this.dictToIndex(dictFieldArray[i], res[dictFieldArray[i]], formSelectData);
        //   }
        //   // this.dictToIndex("vehicle.vehicleType", res["vehicle.vehicleType"], formSelectData);
        //   // this.dictToIndex("vehicle.fuelType", res["vehicle.fuelType"], formSelectData);
        //   // this.dictToIndex("vehicle.useProperty", res["vehicle.useProperty"], formSelectData);
        //   // this.dictToIndex("vehicle.emissionStandard", res["vehicle.emissionStandard"], formSelectData);
        //   // this.dictToIndex("vehicle.plateType", res["vehicle.plateType"], formSelectData);
        //   // this.dictToIndex("buyer.creditType", res["buyer.creditType"], formSelectData);
        //   // this.dictToIndex("seller.creditType", res["seller.creditType"], formSelectData);
        //   formSelectData["vehicle.isImported"] = res["vehicle.isImported"];

        //   this.setData({
        //     formData: res,
        //     formSelectData: formSelectData,
        //     files: image,
        //     filesFlag: filesFlag
        //   });
        }
      });

    }


  },
  //加载字典信息
  loadDict: function(categoryArray, fieldArray) {
    var that = this;
    wx.showLoading({
      title: '数据准备中...',
      mask: true
    })

    // 加载字典相关数组
    getDicts(categoryArray, function(result) {
      wx.hideLoading()
      for (let i = 0; i < categoryArray.length; i++) {
        that.handleDict(result[categoryArray[i]], fieldArray[i]);
      }
    })


    // 返回Promise对象处理
    // getDicts(categoryArray).then(res => {
    //   wx.hideLoading()
    //   for (let i = 0; i < categoryArray.length; i++) {
    //     this.handleDict(businessDict.businessDict[categoryArray[i]], fieldArray[i]);
    //   }
    // })



    // http.request({
    //   url: "/dict/findDict",
    //   data: {
    //     category: category
    //   },
    //   success: res => {
    //     businessDict[category] = res;
    //     this.handleDict(res, field);
    //     wx.hideLoading()
    //   }
    // });
    // } else {
    //   this.handleDict(dictList, field);
    // }
  },
  handleDict: function(dictList, field) {
    let formDict = this.data.formDict;
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    formDict[field] = dictList;
    formData[field] = dictList[0].code;
    formSelectData[field] = 0;
    this.setData({
      formDict: formDict,
      formData: formData,
      formSelectData: formSelectData
    });
  },
  transferData: function(res, field) {
    let buyer = res[field];
    for (let key in buyer) {
      res[field + "." + key] = buyer[key];
    }
    delete res[field];
  },
  dictToIndex: function(field, value, formSelectData) {
    if (value == null || value == "") {
      formSelectData[field] = 0;
      return formSelectData;
    }
    var dict = this.data.formDict[field];
    if (dict != null && dict.length > 0) {
      for (var i = 0; i < dict.length; i++) {
        if (dict[i].code == value) {
          formSelectData[field] = i;
          break;
        }
      }
    }
    return formSelectData;
  },

  bindDateChange: function(e) {
    let formData = this.data.formData;
    formData[e.currentTarget.dataset.field] = e.detail.value;
    this.setData({
      formData: formData
    });
  },
  bindDictChange: function(e) {
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    let field = e.currentTarget.dataset.field;
    let index = e.detail.value;
    formSelectData[field] = index;
    formData[field] = this.data.formDict[field][index]["code"];
    if (field === "transferType" && formData[field] == 2) {
      let dict = this.data.formDict["tradeVehicleType"];
      let index = formSelectData["tradeVehicleType"];
      for (let i = 0; i < dict.length; i++) {
        if (dict[i]["code"] == "TRADE_TURN_OUT") {
          index = i;
        }
      }
      formSelectData["tradeVehicleType"] = index;
      formData["tradeVehicleType"] = "TRADE_TURN_OUT";
    }
    this.setData({
      formData: formData,
      formSelectData: formSelectData
    });
  },
  bindVal: function(e) {
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    let field = e.currentTarget.dataset.field;
    let value = e.detail.value;
    if (field === "vehicle.vin") {
      if (value != null && value.length > 0) {
        if (value.substr(0, 1) == 'L') {
          formData["vehicle.isImported"] = 0;
          formSelectData["vehicle.isImported"] = 0;
        } else {
          formData["vehicle.isImported"] = 1;
          formSelectData["vehicle.isImported"] = 1;
        }
      }
    }
    formData[field] = value;
    this.setData({
      formData: formData,
      formSelectData: formSelectData
    });
  },
  bindRegionChange: function(e) {
    let value = e.detail.value;
    let field = e.currentTarget.dataset.field;
    let formData = this.data.formData;
    formData[field] = value[0] + value[1];
    this.setData({
      formData: formData,
    });
  },
  //验证函数
  initValidate() {
    let fields = this.data.formField;
    let validate = [];
    for (let j = 0; j < fields.length; j++) {
      const rule = {};
      const message = {};
      let formField = fields[j];
      for (let i = 0; i < formField.length; i++) {
        rule[formField[i]["field"]] = formField[i]["rule"];
        message[formField[i]["field"]] = formField[i]["message"];
      }
      let wxValidate = new WxValidate(rule, message);
      validate.push(wxValidate);
    }
    this.WxValidate = validate;
  },
  //调用验证函数
  formSubmit: function(e) {
    const params = e.detail.value;
    //校验表单
    if (!this.WxValidate[this.data.currentStep].checkForm(params)) {
      const error = this.WxValidate[this.data.currentStep].errorList[0];
      $Message({
        content: error.msg,
        type: 'error'
      });
      return false
    }
    this.setData({
      currentStep: this.data.currentStep + 1
    });
  },
  //提交保存数据
  sumbitData: function() {
    let filesField = this.data.filesField;
    let files = this.data.files;
    for (let i = 0; i < filesField.length; i++) {
      if (filesField[i]["required"] === true) {
        if (files[filesField[i]["field"]] == null || files[filesField[i]["field"]] == "") {
          $Message({
            content: filesField[i]["text"] + "必须上传",
            type: 'error'
          });
          return;
        }
      }
    }


    let that = this;
    let tradeVehicleTypeDict = that.data.formDict["tradeVehicleType"];
    let tradeVehicleType = that.data.formData["tradeVehicleType"];
    let commission = 0;
    for (let i = 0; i < tradeVehicleTypeDict.length; i++) {
      if (tradeVehicleTypeDict[i].code == that.data.formData["tradeVehicleType"]) {
        commission = tradeVehicleTypeDict[i].des;
        break;
      }
    }
    that.setData({
      commission: commission
    })

    // wx.showLoading({
    //   title: '正在提交',
    //   mask: true
    // });
    // this.imageToBase64(0, {});
    this.setData({
      show: true
    })
  },

  //
  setdes: function(value) {
    let formdata = this.data.formData;
    formdata['destination'] = value;

    this.setData({
      formData: formdata
    })
  },



  //
  imageToBase64: function(index, images) {
    let field = this.data.filesField[index]["field"];
    index++;
    if (this.data.filesFlag[field] == 1) {
      //说明这张图片是新增
      let file = this.data.files[field];
      wx.getFileSystemManager().readFile({
        filePath: file, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          images[field] = "data:image/jpeg;base64," + res.data;
          // console.info(res.data);
        },
        complete: () => {
          if (index < this.data.filesField.length) {
            this.imageToBase64(index, images);
          } else {
            this.saveData(images);
          }
        }
      })
    } else if (this.data.filesFlag[field] == 0) {
      //说明这张图片是修改时回显的
      images[field] = this.data.formData["image"][field] //直接上传原先的地址
      if (index < this.data.filesField.length) {
        this.imageToBase64(index, images);
      } else {
        this.saveData(images);
      }
    } else {
      if (index < this.data.filesField.length) {
        this.imageToBase64(index, images);
      } else {
        this.saveData(images);
      }
    }
  },
  //弹窗确认
  handleOK: function() {
    this.setData({
      show: false,
    })
    wx.showLoading({
      title: '数据提交中',
      mask: true
    });
    this.imageToBase64(0, {})
  },
  //弹窗取消
  handleCancel: function() {
    this.setData({
      show: false
    })
  },

  saveData: function(images) {
    var that = this;
    let formData = that.data.formData;
    formData["vehicle.brand"] = formData["vehicle.brandModel"];
    formData["vehicle.model"] = formData["vehicle.brandModel"];
    let data = JSON.parse(JSON.stringify(formData));
    for (let key in data) {
      if (data[key] == null) {
        delete data[key];
      }
    }
    delete data["image"];
    if (images != null) {
      for (let key in images) {
        data["image." + key] = images[key];
      }
    }
    // console.log(data);
    http.request({
      url: '/wxApplication/saveApplication',
      data: data,
      success: (res) => {
        let pages = getCurrentPages();
        let prepage = pages[pages.length - 2];
        wx.hideLoading({});

        wx.navigateBack({
          delta: 1,
          complete: function() {
            //保存成功后，页面重新加载数据
            prepage.reloadData();

          }
        });
      },
      error: (res) => {
        wx.hideLoading({});
        $Message({
          content: "提交失败," + res.replace('ServiceException:', ''),
          type: 'error'
        });
      }
    });
  },
  //上一步
  previous: function(e) {
    this.setData({
      currentStep: this.data.currentStep - 1
    });
  },
  //
  handleCancel: function(e) {
    this.setData({
      show: false
    })
  },

  chooseWxImage: function(e) {
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#000",
      success: function(res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.doOcr(e, 'album')
          } else if (res.tapIndex == 1) {
            that.doOcr(e, 'camera')
          }
        }
      }
    })

  },

  //ocr图片识别
  doOcr: function(e, type) {
    var that = this;
    var imageType = 'VL';
    let currentStep = this.data.currentStep;
    if (currentStep == 1) {
      imageType = 'VL';
    } else if (currentStep == 2) {
      imageType = this.data.formData["buyer.creditType"];
    } else if (currentStep == 3) {
      imageType = this.data.formData["seller.creditType"];
    }
    wx.chooseImage({
      sizeType: ['compressed'],
      count: 1,
      sourceType: [type],
      success: function(res) {
        ocr.baiduOcr({
          imageType: imageType,
          filePath: res.tempFilePaths[0],
          success: function(resp) {
            // wx.showLoading({});
            // return;
            var formData = that.data.formData;
            var formSelectData = that.data.formSelectData;
            if (that.data.currentStep == 1) {
              formData["vehicle.vin"] = resp["车辆识别代号"]["words"];
              formData["vehicle.brandModel"] = resp["品牌型号"]["words"];
              // formData["vehicle.brand"] = resp["品牌型号"]["words"];
              // formData["vehicle.model"] = resp["品牌型号"]["words"];
              formData["vehicle.plateNo"] = resp["号牌号码"]["words"];
              formData["vehicle.engineNo"] = resp["发动机号码"]["words"];
              //加入原车主信息  姓名和住址
              formData["seller.name"] = resp["所有人"]["words"];
              formData["seller.residenceAddress"] = resp["住址"]["words"];
              var vehicleTypeDict = that.data.formDict["vehicle.vehicleType"];
              if (vehicleTypeDict != null && vehicleTypeDict.length > 0) {
                var vehicleType = resp["车辆类型"]["words"]
                for (var i = 0; i < vehicleTypeDict.length; i++) {
                  if (vehicleTypeDict[i].name == vehicleType) {
                    formData["vehicle.vehicleType"] = vehicleTypeDict[i].code;
                    formSelectData["vehicle.vehicleType"] = i;
                    break;
                  }
                }
              }
              if (formData["vehicle.vin"].substr(0, 1) == 'L') {
                formData["vehicle.isImported"] = 0;
                formSelectData["vehicle.isImported"] = 0;
              } else {
                formData["vehicle.isImported"] = 1;
                formSelectData["vehicle.isImported"] = 1;
              }
              // console.log(resp);
              var carUsePropertyDict = that.data.formDict["vehicle.useProperty"];
              if (carUsePropertyDict != null && carUsePropertyDict.length > 0) {
                var userProperty = resp["使用性质"]["words"];
                for (var i = 0; i < carUsePropertyDict.length; i++) {
                  if (carUsePropertyDict[i].name == userProperty) {
                    formData["vehicle.useProperty"] = carUsePropertyDict[i].code;
                    formSelectData["vehicle.useProperty"] = i;
                    break;
                  }
                }
              }
            } else if (that.data.currentStep == 2) {
              if (imageType == "P1") {
                formData["buyer.creditNo"] = resp["公民身份号码"]["words"];
                formData["buyer.name"] = resp["姓名"]["words"];
                //formData["buyer.censusAddress"] = resp["住址"]["words"];
                formData["buyer.residenceAddress"] = resp["住址"]["words"];
              } else if (imageType == 'C3') {
                formData["buyer.creditNo"] = resp["社会信用代码"]["words"];
                formData["buyer.name"] = resp["单位名称"]["words"];
                //formData["buyer.censusAddress"] = resp["住址"]["words"];
                formData["buyer.residenceAddress"] = resp["地址"]["words"];
              }
            } else if (that.data.currentStep == 3) {
              if (imageType == "P1") {
                formData["seller.creditNo"] = resp["公民身份号码"]["words"];
                formData["seller.name"] = resp["姓名"]["words"];
                //formData["seller.censusAddress"] = resp["住址"]["words"];
                formData["seller.residenceAddress"] = resp["住址"]["words"];
              } else if (imageType == 'C3') {
                formData["seller.creditNo"] = resp["社会信用代码"]["words"];
                formData["seller.name"] = resp["单位名称"]["words"];
                //formData["seller.censusAddress"] = resp["住址"]["words"];
                formData["seller.residenceAddress"] = resp["地址"]["words"];
              }
            }
            that.setData({
              formData: formData,
              formSelectData: formSelectData
            });
          },
        });

        let fileField = that.data.currentStep == 1 ? "vehicleLicense" :
          that.data.currentStep == 2 ? "buyerCreditFront" : "sellerCreditFront";
        let files = that.data.files;
        files[fileField] = res.tempFilePaths[0];
        var filesFlag = that.data.filesFlag;
        filesFlag[fileField] = 1; // 0表示这是之前上传过的，1表示是新上传的
        that.setData({
          files: files,
          filesFlag: filesFlag
        });
      }
    });
  },
  //上传图片
  chooseImage: function(e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['compressed'],
      //sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      //sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      count: 1,
      success: function(res) {
        var files = that.data.files;
        files[e.currentTarget.dataset.field] = res.tempFilePaths[0];
        var filesFlag = that.data.filesFlag;
        filesFlag[e.currentTarget.dataset.field] = 1; // 0表示这是之前上传过的，1表示是新上传的
        that.setData({
          files: files,
          filesFlag: filesFlag
        });
      }
    })
  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.img, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.img] // 需要预览的图片http链接列表
    })
  },
  deleteImage: function(e) {
    var files = this.data.files;
    files[e.currentTarget.dataset.field] = null;
    var filesFlag = this.data.filesFlag;
    filesFlag[e.currentTarget.dataset.field] = null; // 0表示这是之前上传过的，1表示是新上传的
    this.setData({
      files: files
    });
  },

  //企业和个人orc识别按钮切换
  tabChange: function(e) {
    //显示确认框
    let field = e.currentTarget.dataset.field;
    let creditType = e.currentTarget.dataset.credit;
    let files = this.data.files;
    this.setData({
      confirmField: field,
      confirmValue: creditType,
      // confirmShow: true
    });
    let that = this;

    if (field == "buyerCreditFront") {
      wx.showModal({
        title: '提示',
        content: '切换车主类型，将清空买家车主证件信息！确认切换？',
        success(res) {
          if (res.confirm) {
            that.handleConfirmOk()
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else if (field == "sellerCreditFront") {
      that.handleConfirmOk()
    }
    // let formData = this.data.formData;
    // let field = e.currentTarget.dataset.field;
    // let creditType = e.currentTarget.dataset.credit;
    // if (field == "buyerCreditFront") {
    //   //买家
    //   formData["buyer.creditType"] = creditType;
    // } else if (field == "sellerCreditFront") {
    //   //卖家
    //   formData["seller.creditType"] = creditType;
    // }
    // this.setData({
    //   formData: formData,
    // });
  },
  //二维码识别扫描
  getQRCode: function(e) {
    var _this = this;
    let formData = this.data.formData;
    wx.scanCode({ //扫描API
      success: function(res) {
        formData[e.currentTarget.dataset.field] = res.result;
        _this.setData({
          formData: formData,
        });
      }
    })
  },
  handleConfirmOk: function() {
    let formData = this.data.formData;
    let field = this.data.confirmField;
    let creditType = this.data.confirmValue;
    let files = this.data.files;
    if (field == "buyerCreditFront") {
      //买家
      formData["buyer.creditType"] = creditType;
      formData["buyer.creditNo"] = null;
      formData["buyer.name"] = null;
      formData["buyer.residenceAddress"] = null;
      files["buyerCreditFront"] = null;
    } else if (field == "sellerCreditFront") {
      //卖家
      formData["seller.creditType"] = creditType;
      // formData["seller.creditNo"] = null;
      // formData["seller.name"] = null;
      // formData["seller.residenceAddress"] = null;
      files["sellerCreditFront"] = null;
    }
    this.setData({
      formData: formData,
      // confirmShow: false,
      files: files
    });
  },
  //chooseCity
  chooseCity: function(e) {
    let filed = e.currentTarget.dataset.field;
    let formData = this.data.formData;
    // console.log(formData[filed]);
    wx.navigateTo({
      url: '/pages/itemChose/index?filed=' + filed,
    })
  },
  handleConfirmCancel: function() {
    this.setData({
      confirmShow: false
    });
  },
})